<template>
  <div>
    <!-- 问卷标题 -->
    <h1 class="survey-title">{{ formData.title }}</h1>

    <!-- 问题类型选择器 -->
    <el-select v-model="newQuestionType" placeholder="选择问题类型" style="width: 200px" @change="resetNewQuestion">
      <el-option label="单选问题" value="radio"></el-option>
      <el-option label="多选问题" value="checkbox"></el-option>
      <el-option label="日期问题" value="date"></el-option>
      <el-option label="单行文本框" value="text"></el-option>
      <el-option label="多行文本框" value="textarea"></el-option>
    </el-select>

    <!-- 添加问题按钮 -->
    <el-button @click="addQuestion">添加问题</el-button>

    <!-- 重置按钮 -->
    <el-button @click="resetSurvey" type="warning" size="small" style="margin-left: 10px;">重置</el-button>

    <el-form :model="formData">
      <draggable :options="{ group: 'formData.questions' }" :list="formData.questions"
                 :group="{ name: 'questions' }"
                 @start="drag=true"
                 @end="drag=false"
                 @change="onDragChange">
        <div v-for="(question, index) in formData.questions" :key="question.id">
          <el-form-item :key="question.id">
            <component :is="getComponentName(question.type)" :question="question" />
            <!-- 删除按钮 -->
            <el-button @click="deleteQuestion(question.id)" type="danger" size="small">删除</el-button>
          </el-form-item>
        </div>
      </draggable>
    </el-form>

    <!-- 保存按钮 -->
    <el-button @click="saveSurvey">保存问卷</el-button>
  </div>
</template>

<script>
import QuestionRadio from './RadioQuestion.vue'; // 引入单选问题组件
import QuestionCheckbox from './CheckboxQuestion.vue'; // 引入多选问题组件
import QuestionDate from './DateQuestion.vue'; // 引入日期问题组件
import QuestionText from './TextQuestion.vue'; // 引入单行文本框问题组件
import QuestionTextArea from './TextAreaQuestion.vue' // 引入多行文本框问题组件
import draggable from 'vuedraggable';
import {surveyQuestionUpdateBySurveyId} from "../../../../api/survey/surveyInfo";

export default {
  components: {
    QuestionRadio,
    QuestionCheckbox,
    QuestionDate,
    QuestionText,
    QuestionTextArea,
    draggable
  },
  props: {
    form: Object,  // 接收父组件传递的问卷数据
    questionForm: Array
  },
  created(){
    // 将父组件传递的初始数据存储在 resetQuestionForm 中
    this.resetQuestionForm = JSON.parse(JSON.stringify(this.questionForm));  // 深拷贝，防止直接引用问题列表
  },
  watch: {
    // 当父组件的 form 或 questionForm 发生变化时，更新子组件的数据
    form(newForm) {
      this.formData.title = newForm.title;
    },
    questionForm(newQuestions) {
      // 设置sort顺序为index+1
      newQuestions.forEach((question, index) => {
        // 更新 sort 为 index + 1
        question.sort = index + 1;
      });
      // 当问题列表发生变化时，更新 formData.questions 和 resetQuestionForm
      this.resetQuestionForm = JSON.parse(JSON.stringify(newQuestions));
      this.formData.questions = newQuestions;
      console.log(this.formData.questions)
    }
  },
  data() {
    return {
      formData: {
        title: this.form.title,
        questions: this.questionForm
      },
      resetQuestionForm: [],  // 用于保存初始问卷问题
      newQuestionType: '',  // 当前选择的题目类型
      drag: false // 拖拽标识
    };
  },
  methods: {

    // 重置问卷
    resetSurvey() {
      // 重置标题
      this.formData.title = this.form.title;

      // 重置问题列表为父组件传递的初始问题列表
      this.formData.questions = JSON.parse(JSON.stringify(this.resetQuestionForm));
    },

    // 添加新问题
    addQuestion() {
      if (!this.newQuestionType) {
        this.$message.error('请选择问题类型');
        return;
      }

      const newQuestion = {
        id: null,  // 生成一个唯一的 ID
        type: this.newQuestionType,
        text: '',  // 问题文本
        sort:this.formData.questions.length,
        options: this.newQuestionType === 'radio' || this.newQuestionType === 'checkbox' ? [''] : [], // 只有选择题才有选项
        selectedOptions: [] // 已选择的选项
      };

      this.formData.questions.push(newQuestion);
    },

    // 删除问题
    deleteQuestion(questionId) {
      const index = this.formData.questions.findIndex(question => question.id === questionId);
      if (index !== -1) {
        this.formData.questions.splice(index, 1); // 从数组中删除问题
      }
    },

    // 获取对应类型的子组件名称
    getComponentName(type) {
      switch (type) {
        case 'radio':
          return 'QuestionRadio';
        case 'checkbox':
          return 'QuestionCheckbox';
        case 'date':
          return 'QuestionDate';
        case 'text':
          return 'QuestionText';
        case 'textarea':
          return 'QuestionTextArea';
        default:
          return null;
      }
    },

    // 重置新问题
    resetNewQuestion() {
      if (this.newQuestionType === 'radio' || this.newQuestionType === 'checkbox') {
        this.newQuestion = {options: ['']};
      } else if (this.newQuestionType === 'date') {
        this.newQuestion = {text: ''};
      } else {
        this.newQuestion = {text: ''};
      }
    },

    // 拖拽移动时的处理函数
    onDragMove(evt) {
      console.log("拖拽新的问题顺序：", this.formData.questions);
    },
    onDragChange(event) {
      this.formData.questions.forEach((question, index) => {
        question.sort = index + 1;  // 更新排序字段
      });
    },
    transformData() {
      const surveyId = this.formData.surveyId;
      const currentTime = new Date(); // 当前时间

      // 转换逻辑
      const transformedQuestions = this.formData.questions.map((question) => {
        // 判断 question.type 是否是 "text", "textarea", 或 "date"
        const surveyOptionList = ["text", "textarea", "date"].includes(this.mapQuestionType(question.type))
            ? [] // 如果是上述类型，返回空数组
            : question.options.map((option) => ({
              optionId: option.optionId,
              questionId: question.id,
              optionText: option.optionText,
              optionSort: option.optionSort,
            }));

        return {
          questionId: question.id,
          surveyId: surveyId, // 使用固定的 surveyId
          sort: question.sort,
          questionText: question.text,
          questionType: this.mapQuestionType(question.type),
          createTime: currentTime,
          updateTime: currentTime,
          surveyOptionList: surveyOptionList, // 使用计算后的 surveyOptionList
        };
      });

      // 处理转换后的数据
      this.transformedData = transformedQuestions;
    },

    // 映射题目类型（radio, checkbox, date, text）到枚举值
    mapQuestionType(type) {
      const questionTypeMap = {
        radio: "radio",  // 或者你可以使用枚举类型的值
        checkbox: "checkbox",
        date: "date",
        text: "text",
        textarea: "textarea",
      };
      return questionTypeMap[type] || null; // 默认 "UNKNOWN" 类型
    },

    // 保存问卷
    saveSurvey() {
      this.transformData();
      const reqData = {}
      reqData.surveyId = this.form.surveyId;
      reqData.surveyQuestion = this.transformedData
      console.log(this.formData);
      console.log(reqData);
      surveyQuestionUpdateBySurveyId(reqData).then(response => {
        this.$message.success('问卷保存成功');
      });
    }
  }
};

</script>

<style scoped>
.survey-title {
  text-align: center;
  margin-bottom: 20px;
}

.el-form-item {
  cursor: move; /* 设置可拖拽的样式 */
  margin-bottom: 10px;
}

.el-button {
  margin-top: 10px;
}

.el-select {
  margin-bottom: 20px;
}

.sortable-drag{
  display: block !important;
  opacity: 1 !important;
}

</style>
